package com.cskaoyan.controller.wx.address;

import com.cskaoyan.bean.MarketAddress;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.bo.wx.address.DeleteForAdressBo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.vo.wx.address.AddressOfListVo;
import com.cskaoyan.service.wx.address.AddressService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Mr.Tang
 * @since 2022/09/09 23:31
 */
@RestController
@RequestMapping("wx/address")
public class AddressController {
    private static final Integer FAKEID = 1;
    @Autowired
    AddressService addressService;


    @RequestMapping("list")
    public BaseRespVo listForAddress() {
        // 等到可以用时放开注释
        // 使用SecurityUtils.getSubject()拿到当前登录用户的信息
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();
//        Integer userId = FAKEID;
        AddressOfListVo addressOfListVo = addressService.listForAddress(userId);


        return BaseRespVo.ok(addressOfListVo);
    }

    /**
     * 收货地址详情
     * Request URL: http://localhost:8083/wx/address/detail?id=1
     * @return
     */
    @RequestMapping("detail")
    public BaseRespVo detailForAddress(Integer id) {
        MarketAddress addressOfDetailVO = addressService.detailForAddress(id);

        return BaseRespVo.ok(addressOfDetailVO);

    }

    /**
     * 修改和新增地址
     * {"errno":0,"data":37,"errmsg":"成功"}
     * @return
     */
    @RequestMapping("save")
    public BaseRespVo saveForAddress(@RequestBody MarketAddress marketAddress) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();
        marketAddress.setUserId(userId);
        // 如果id等于0就新增
        if(marketAddress.getId()==0) {
           int code = addressService.insertAdress(marketAddress);
            return BaseRespVo.ok(code);
        }else {
        // 否则就修改
           int code = addressService.updateAddress(marketAddress);
            return BaseRespVo.ok(code);
        }

    }


    /**
     * 删除
     */

    @RequestMapping("delete")
    public BaseRespVo deleteForAdress(@RequestBody DeleteForAdressBo deleteForAdressBo) {
        int addressId = deleteForAdressBo.getId();
        addressService.deleteForAdress(addressId);
        return BaseRespVo.ok(null);
    }


}
